package com.gmzg.gmzgoffice.contacts;


import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.test.mock.MockApplication;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.gmzg.gmzgoffice.GMZGApplication;
import com.gmzg.gmzgoffice.R;
import com.gmzg.gmzgoffice.contacts.adapters.ContactListAdapter;
import com.gmzg.gmzgoffice.contacts.model.ContactItem;
import com.gmzg.gmzgoffice.message.ChatActivity;
import com.hyphenate.EMContactListener;
import com.hyphenate.EMConversationListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMChatManager;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMContactManager;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessageBody;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.exceptions.HyphenateException;

import java.io.FileInputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * A simple {@link Fragment} subclass.
 */
public class ContactsFragment extends Fragment implements AdapterView.OnItemClickListener, EMConversationListener, EMMessageListener, AdapterView.OnItemLongClickListener {
    private InputMethodManager inputMethodManager;
    private Handler mHandler = new MyHandler(this);

    private static class MyHandler extends Handler {
        WeakReference<Fragment> mFragmentReference;
        public MyHandler(Fragment fragment) {
            mFragmentReference=new WeakReference<Fragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            final ContactsFragment context =  (ContactsFragment)mFragmentReference.get();
            Activity activity = context.getActivity();
            switch (msg.what) {
                case 199: // 添加好友刷新列表
                    Object obj = msg.obj;
                    if (obj != null) {
                        if (obj instanceof List) {
                            List list = (List) obj;
//                            for (Object s : list) {
//                                Log.d("ddddddddd", "handleMessage: "+ ((String) s));
//                            }
                            context.mContacts.clear();
                            for (Object o : list) {
                                ContactItem item = new ContactItem();
                                item.setName((String) o);
                                context.mContacts.add(item);
                            }
                            context.mAdapter.notifyDataSetChanged();
                            if (activity != null) {
                                Toast.makeText(activity, "添加成功", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                    break;
                case 100://没有查找到该好友,或者好友不在线
                    Object obj1 = msg.obj;
                    if (obj1 != null) {
                        if (obj1 instanceof String) {
                            String s = (String) obj1;
                            if (activity != null) {
                                Toast.makeText(activity, s, Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                    break;
                case 198://删除好友刷新
                    Object obj2 = msg.obj;
                    if (obj2 != null) {
                        if (obj2 instanceof List) {
                            List list = (List) obj2;
                            context.mContacts.clear();
                            for (Object o : list) {
                                ContactItem item = new ContactItem();
                                item.setName((String) o);
                                context.mContacts.add(item);
                            }
                            context.mAdapter.notifyDataSetChanged();
                            if (activity != null) {
                                Toast.makeText(activity, "删除成功", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                    break;
                case 197://首次刷新
                    Object obj3 = msg.obj;
                    if (obj3 != null) {
                        if (obj3 instanceof List) {
                            List list = (List) obj3;
                            context.mContacts.clear();
                            for (Object o : list) {
                                ContactItem item = new ContactItem();
                                item.setName((String) o);
                                context.mContacts.add(item);
                            }
                            context.mAdapter.notifyDataSetChanged();
                        }
                    }
                    break;
                case 196:
                    // 有好友添加，自动刷新列表
                    Object obj4 = msg.obj;
                    if (obj4 != null) {
                        if (obj4 instanceof List) {
                            List list = (List) obj4;
                            context.mContacts.clear();
                            for (Object o : list) {
                                ContactItem item = new ContactItem();
                                item.setName((String) o);
                                context.mContacts.add(item);
                            }
                            context.mAdapter.notifyDataSetChanged();
                            if (activity != null) {
                                Toast.makeText(activity, "有新好友了", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                    break;
            }
        }
    }

    private boolean isClickAdd;

    private ContactListAdapter mAdapter;
    //好友列表
    private List<ContactItem> mContacts;

    /**
     * 添加好友时使用
     */
    private EditText mEditAddAccount;

    //    private SwipeRefreshLayout mRefreshLayout;
    private String mName;


    public ContactsFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences sp = getContext().getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        mName = sp.getString("user", null);
        Log.d("ddddddddd", "onCreate: " + ((GMZGApplication) getActivity().getApplication()).getUserName());
        inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        isClickAdd = false;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View ret = inflater.inflate(R.layout.fragment_contacts, container, false);
        //设置toolbar
        Toolbar toolbar = (Toolbar) ret.findViewById(R.id.my_toolbar);
        setHasOptionsMenu(true);
        ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
        //去掉默认的标题
        toolbar.setTitle("");

        if (mName != null) {
            ListView listView = (ListView) ret.findViewById(R.id.contact_list);
            if (listView != null) {
                mContacts = new ArrayList<>();
                mAdapter = new ContactListAdapter(getContext(), mContacts);
                listView.setAdapter(mAdapter);
                listView.setOnCreateContextMenuListener(this);
                listView.setOnItemLongClickListener(this);
                listView.setOnItemClickListener(this);
            }

            mEditAddAccount = (EditText) ret.findViewById(R.id.contact_add_name);

//            mRefreshLayout = (SwipeRefreshLayout) ret.findViewById(R.id.contact_refresh);
//            mRefreshLayout.setOnRefreshListener(this);

//            //刷新联系人列表
            ContactListThread thread = new ContactListThread();
            thread.start();
            //实时更新用户列表,没两秒刷新一次
//            refreshHandler.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    //刷新联系人列表
//                    AutoContactListThread thread = new AutoContactListThread();
//                    thread.start();
//                    //一直给自己发消息
//                    refreshHandler.postDelayed(this,2000);
//                }
//            },2000);

            //监听好友状态事件
            EMClient.getInstance().contactManager().setContactListener(new EMContactListener() {
                @Override
                public void onContactAgreed(String username) {
                    //好友请求被同意
                }

                @Override
                public void onContactRefused(String username) {
                    //好友请求被拒绝
                }

                @Override
                public void onContactInvited(String username, String reason) {
                    //收到好友邀请

                }

                @Override
                public void onContactDeleted(String username) {
                    //被删除时回调此方法
                }

                @Override
                public void onContactAdded(String username) {
                    //增加了联系人时回调此方法
                    //自动刷新联系人列表
                    AutoContactListThread thread = new AutoContactListThread();
                    thread.start();
                }
            });


            // !!! 注册回话通知

            EMChatManager emChatManager = EMClient.getInstance().chatManager();

            emChatManager.addConversationListener(this);

            emChatManager.addMessageListener(this);
        }
        return ret;
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        Log.d("ddddddd", "onCreateOptionsMenu()");
        menu.clear();
        inflater.inflate(R.menu.contacts_toolbar_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_add_friends:
                //隐藏软键盘
                if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
                    if (getActivity().getCurrentFocus() != null)
                        inputMethodManager.hideSoftInputFromWindow
                                (getActivity()
                                                .getCurrentFocus()
                                                .getWindowToken(),
                                        InputMethodManager.HIDE_NOT_ALWAYS);
                }
                String toAddName = mEditAddAccount.getText().toString().trim();
                boolean isContain = false;
                if (toAddName.length() > 0) {
                    //检查自己的好友
                    int len = mContacts.size();
                    for (int i = 0; i < len; i++) {
                        String name = mContacts.get(i).getName();
                        if (name.equals(toAddName)) { // 相同，表示已经有这个人了
                            isContain = true;
                            Toast.makeText(getContext(), "您已经添加了这个好友了，请不要重复添加", Toast.LENGTH_SHORT).show();
                            break;
                        }
                    }
                    if (!isContain) {
                        //不包含，则添加
                        isClickAdd = true;
                        AddContactThread thread = new AddContactThread(toAddName);
                        thread.start();
                    }
                } else {
                    Toast.makeText(getContext(), "请输入要添加好友的名字", Toast.LENGTH_SHORT).show();
                }
                mEditAddAccount.setText("");
                return true;

            default:
                mEditAddAccount.setText("");
                return super.onOptionsItemSelected(item);
        }
    }

    //长按好友列表中的某一项，将该好友删除
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        final ContactItem item = mContacts.get(position);
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("确定要删除这个好友么");
        // 设置单选列表，点击的时候，调用 onClick 方法，which 就是选择item的数组下标
        builder.setItems(new String[]{"确定", "取消"},
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int which) {
                        switch (which) {
                            case 0:
                                try {
                                    EMClient.getInstance().contactManager().deleteContact(item.getName());
                                    //刷新联系人列表
                                    ContactListThread thread = new ContactListThread();
                                    thread.start();
                                } catch (HyphenateException e) {
                                    e.printStackTrace();
                                    Log.d("ddddddddd", "onClick: 删除失败");
                                }
                                break;
                            case 1:
                                //点击取消不做任何事
                                break;
                        }
                    }
                });

        AlertDialog dialog = builder.create();

        dialog.show();
        return true;
    }

    private class AutoContactListThread extends Thread {
        @Override
        public void run() {
            //获取好友联系人
            EMContactManager contactManager = EMClient.getInstance().contactManager();
            List<String> allContactsFromServer = null;
            try {
                allContactsFromServer = contactManager.getAllContactsFromServer();
            } catch (HyphenateException e) {
                e.printStackTrace();
            }
            // 去除重复的数据
            ArrayList<String> temp = new ArrayList<>();
            for (String s : allContactsFromServer) {
                if (!temp.contains(s)) {
                    temp.add(s);
                }
            }
            Message message = mHandler.obtainMessage(196);
            message.obj = temp;
            mHandler.sendMessage(message);
        }
    }

    private class ContactListThread extends Thread {
        @Override
        public void run() {
            try {
                //获取好友联系人
                EMContactManager contactManager = EMClient.getInstance().contactManager();
                List<String> allContactsFromServer = contactManager.getAllContactsFromServer();
                // 去除重复的数据
                ArrayList<String> temp = new ArrayList<>();
                for (String s : allContactsFromServer) {
                    if (!temp.contains(s)) {
                        temp.add(s);
                    }
                }
                int newListSize = temp.size();
                //比较从服务器返回过来的列表，和当前列表的变化，看有没有新增
                int oldListSize = mContacts.size();
                if (oldListSize == 0 && newListSize == 0) {
                    //没有好友，什么也不做
                } else {
                    if (newListSize == oldListSize) {
                        if (isClickAdd) {
                            Message message = mHandler.obtainMessage(100);
                            message.obj = "没有这个好友，或者该好友不再线，请从新输入";
                            mHandler.sendMessage(message);
                            isClickAdd = false;
                        } else {
                            //切换页面刷新
                            Message message = mHandler.obtainMessage(197);
                            message.obj = temp;
                            mHandler.sendMessage(message);
                        }
                    } else if (newListSize > oldListSize) {
                        if (oldListSize == 0 && !isClickAdd) {
                            //首次启动，只有一个好友
                            //在没有好友的时候，添加一个好友
                            //首次刷新
                            Message message = mHandler.obtainMessage(197);
                            message.obj = temp;
                            mHandler.sendMessage(message);
                        } else {
                            //添加好友
                            isClickAdd = false;
                            Message message = mHandler.obtainMessage(199);
                            message.obj = temp;
                            mHandler.sendMessage(message);
                        }
                    } else if (newListSize < oldListSize) {
                        //删除好友
                        Message message = mHandler.obtainMessage(198);
                        message.obj = temp;
                        mHandler.sendMessage(message);
                    }
                }

            } catch (HyphenateException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onDestroy() {
        EMChatManager emChatManager = EMClient.getInstance().chatManager();

        emChatManager.removeConversationListener(this);
        emChatManager.removeMessageListener(this);
        super.onDestroy();
    }


    private class AddContactThread extends Thread {

        private String account;

        public AddContactThread(String account) {
            this.account = account;
        }

        @Override
        public void run() {
            //参数为要添加的好友的username和添加理由
            try {
                EMClient.getInstance().contactManager().addContact(account, "我是你的朋友，快点加吧");
            } catch (HyphenateException e) {
                e.printStackTrace();
            }

            // 刷新列表
            ContactListThread thread = new ContactListThread();
            thread.start();
        }
    }


    ///////////////////////////////////////////////////////////////////////////
// listView的点击事件
///////////////////////////////////////////////////////////////////////////
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // 需要给哪个联系人发送消息
        String toUserName = mContacts.get(position).getName();
        Intent intent = new Intent(getContext(), ChatActivity.class);
        intent.putExtra("toUserName", toUserName);
//        Toast.makeText(getContext(), "发送给"+toUserName, Toast.LENGTH_SHORT).show();
        startActivity(intent);
    }

    ///////////////////////////////////////////////////////////////////////////
// 下拉刷新的监听事件
///////////////////////////////////////////////////////////////////////////
//    @Override
//    public void onRefresh() {
//        ContactListThread thread = new ContactListThread();
//        thread.start();
//    }

    ///////////////////////////////////////////////////////////////////////////
// 会话监听
///////////////////////////////////////////////////////////////////////////
    @Override
    public void onCoversationUpdate() {

    }

    ///////////////////////////////////////////////////////////////////////////
// 消息监听
///////////////////////////////////////////////////////////////////////////

    /**
     * 用户收到消息回调
     *
     * @param list
     */
    @Override
    public void onMessageReceived(List<EMMessage> list) {
        for (EMMessage emMessage : list) {
            String from = emMessage.getFrom();
            EMMessageBody body = emMessage.getBody();
            if (body instanceof EMTextMessageBody) {
                EMTextMessageBody textMessageBody = (EMTextMessageBody) body;
                String message = textMessageBody.getMessage();
                Log.d("MyList", "message from " + from + " msg: " + message);

//                for (ContactItem contact : mContacts) {
//                    String name = contact.getName();
//                    if(name.equals(from)){ // 相同，代表同一个人发的
//                        int messageCount = contact.getMessageCount();
//                        messageCount++;
//                        contact.setMessageCount(messageCount);
//                        break;
//                    }
//                }
//                mAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> list) {

    }

    @Override
    public void onMessageReadAckReceived(List<EMMessage> list) {

    }

    @Override
    public void onMessageDeliveryAckReceived(List<EMMessage> list) {

    }

    @Override
    public void onMessageChanged(EMMessage message, Object o) {

    }


}
